package com.liu.project.utils;




import com.liu.project.pojo.LoginUser;
import com.liu.project.pojo.SysRole;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @program: project
 * @description: JWT工具类
 * @author: 86187
 * @create: 2022-03-03 14:57
 **/


@Component
public class JwtUtils {

//    token 头
    public static  String TOKEN_HEADER = "Authorization";
//token前缀
    public static  String TOKEN_PREFIX = "Bearer ";

    /**
     * 自定义用户信息
     */
    private static  String ROLE_CLAIMS = "role";

    // 秘钥
    // token秘钥  太短会报错
    public  static String SECRET = "aHR0cHM6Ly9teS5vc2NoaW5hLm5ldC91LzM2ODE4Njgqwsdxddddz";
    /**
     * JWT的发行人
     */
    private static  String ISS = "LIUSHIZE";

    /**
     * 过期时间是3600秒，既是1个小时
     */
    public static  long EXPIRATION = 3600L * 1000;
    /**
     * 选择了记住我之后的过期时间为7天
     */
    public static  long EXPIRATION_REMEMBER = 604800L * 1000;

    /**
     * 生成token
     * @param loginUser
     * @return
     */
    public String createToken (LoginUser loginUser,boolean isRememberMe){
        long expiration = isRememberMe ?EXPIRATION_REMEMBER :EXPIRATION;
        HashMap<String, Object> map = new HashMap<>();
        map.put(ROLE_CLAIMS,loginUser.getAuthorities());


        return Jwts.builder().signWith(SignatureAlgorithm.HS256,SECRET)//加密算法
                .setClaims(map)//自定义信息
                .setIssuer(ISS)//jwt发行人
                .setSubject(loginUser.getUsername())//jwt面向的用户
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+expiration))
                .compact();
    }


    /**
     * 从token获取用户信息
     *
     * @param token
     * @return
     */
    public static String getUsername(String token)  {
        String username=null;
        try {
            return username=getTokenBody(token).getSubject();
        } catch (Exception e) {
           return username;
        }
    }

    /**
     * 从token中获取用户角色
     *
     * @param token
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List<SysRole> getUserRole(String token) {
        List<SysRole> sysRoles = (List<SysRole>) getTokenBody(token).get(ROLE_CLAIMS);
        return sysRoles;
    }

    /**
     * 是否已过期
     *
     * @param token
     * @return
     */
    public static boolean isExpiration(String token)  {
        return getTokenBody(token).getExpiration().before(new Date());
    }

    private static Claims getTokenBody(String token)  {
        return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
    }

    /**
     * 验证token
     *
     * @param token
     * @param loginUser
     * @return
     */
    public static boolean validateToken(String token, LoginUser loginUser){
        final String username = getUsername(token);
        return (username.equals(loginUser.getUsername()) && isExpiration(token) == false);
    }
    /**
     * 获取token失效时间
     * @param token
     * @return
     */
    public Date getExpirationDateFromToken(String token)   {
        return getTokenBody(token).getExpiration();
    }

    /**
     * 获取jwt发布时间
     */
    public Date getIssuedAtDateFromToken(String token)  {
        return getTokenBody(token).getIssuedAt();
    }

}


